package com.sunrise.generico.bean;

import java.io.Serializable;
import java.security.SecureRandom;
import java.util.Collection;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.event.ComponentSystemEvent;
import javax.mail.MessagingException;

import lombok.Getter;
import lombok.Setter;

import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.sunrise.configuracoes.repositorio.iface.StatusNotificacaoDao;
import com.sunrise.crm.repositorio.iface.UsuarioDao;
import com.sunrise.generico.entidade.StatusNotificacao;
import com.sunrise.generico.entidade.Usuario;
import com.sunrise.generico.util.ConfigUtil;
import com.sunrise.generico.util.EmailUtil;
import com.sunrise.generico.util.LocationUtils;
import com.sunrise.generico.util.MessagesUtil;

@ManagedBean
@Scope(value = "session")
@Controller
public class SessionBean implements Serializable {

	private static final long serialVersionUID = 7283481641262973860L;

	private LocationUtils locationUtils;

	@Resource(name = "usuarioDaoImpl")
	@Getter
	private UsuarioDao usuarioDao;

	@Resource(name = "statusNotificacaoDaoImpl")
	@Getter
	private StatusNotificacaoDao statusNotificacaoDao;

	@Getter
	@Setter
	private Usuario usuarioLogado;

	@Getter
	@Setter
	private String info;

	@Getter
	@Setter
	private String idCampo;

	@Getter
	@Setter
	private String login;

	@Getter
	@Setter
	private Collection<StatusNotificacao> notificacoes;

	public LocationUtils getLocationUtils() {
		if (locationUtils == null) {
			locationUtils = new LocationUtils();
		}
		return locationUtils;
	}

	public void clearAll() {
		locationUtils = null;
	}

	public void loadUser(ComponentSystemEvent event) {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		Usuario user = getUsuarioDao().buscarPorUsername(auth.getName());
		String[] primeiroNome = user.getNome().split(" ");
		if (primeiroNome.length > 1) {
			if(primeiroNome.length > 2){
				user.setPrimeiroNome(primeiroNome[0] + " " + primeiroNome[1]);
			}else{
				user.setPrimeiroNome(primeiroNome[0]);
			}
		}
		setNotificacoes(carregarNotificacoes(user.getId()));
		this.setUsuarioLogado(user);
	}

	public Collection<StatusNotificacao> carregarNotificacoes(Long userID) {
		List<StatusNotificacao> notificacoes = getStatusNotificacaoDao().listarPorUsuario(userID);
		if (notificacoes.size() >= 8) {
			return notificacoes.subList(0, 8);
		}
		return notificacoes;
	}

	public void onFocus(AjaxBehaviorEvent evento) {
		setInfo(MessagesUtil.getInfosKey(evento.getComponent().getId()));
	}

	public void onBlur(AjaxBehaviorEvent evento) {
		setInfo("");
	}

	public void buscarMensagem() {
		String[] idCampoSplit = idCampo.split(":");
		String parteFinal = idCampoSplit[idCampoSplit.length - 1];
		if (parteFinal != null) {
			setInfo(MessagesUtil.getInfosKey(parteFinal));
		} else {
			setInfo("");
		}

	}

	public void limparMensagem() {
		setInfo("");
	}

	public String recuperarSenha() throws MessagingException {
		Collection<Usuario> usuarios = getUsuarioDao().listarPorLoginEmail(getLogin());
		for (Usuario usuario : usuarios) {
			String html = EmailUtil.htmlEnviarSenha();
			html = html.replace("nomeUsuario", usuario.getNome());
			html = html.replace("httpEndereco", ConfigUtil.getProperty("enderecoSenha") + obterChaveRecuperarSenha());
			EmailUtil.sendEmailUsingTemplate(usuario.getEmail(), html, "Recuperar Senha");
		}
		return "";

	}

	private static String obterChaveRecuperarSenha() {
		String crs = "?crs=";
		crs += randomString(256);
		return crs;
	}

	public static String randomString(int length) {
		char[] charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789zxcvbnmasdfghjklqwertyuiop".toCharArray();
		Random random = new SecureRandom();
		char[] result = new char[length];
		for (int i = 0; i < result.length; i++) {
			int randomCharIndex = random.nextInt(charSet.length);
			result[i] = charSet[randomCharIndex];
		}
		return new String(result);
	}
}